package com.example.module_hp_zao_yin_media.fragment;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.module_hp_zao_yin_media.R;
import com.example.module_hp_zao_yin_media.activity.HpZaoYinVideoInfoActivity;
import com.example.module_hp_zao_yin_media.base.BaseMvvmActivity;
import com.example.module_hp_zao_yin_media.base.BaseViewModel;
import com.example.module_hp_zao_yin_media.databinding.ActivityHpZaoYinVideoBinding;
import com.example.module_hp_zao_yin_media.util.AudioRecordVideoDemo;
import com.example.module_hp_zao_yin_media.util.AudioRecordVideoDemo2;
import com.example.module_hp_zao_yin_media.util.Utils;
import com.fwlst.lib_base.fragment.BaseMvvmFragment;
import com.fwlst.lib_base.utils.AdUtils;
import com.fwlst.lib_base.utils.BaseUtils;
import com.fwlst.lib_base.utils.JtXXPermissions;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraView;
import com.otaliastudios.cameraview.VideoResult;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;
public class HpZaoYinVideoFragment extends BaseMvvmFragment<ActivityHpZaoYinVideoBinding, BaseViewModel> {
    private AudioRecordVideoDemo2 audioRecordDemo;
    private List<Double> numArr = new ArrayList<>();
    private Handler mHandler;
    private int timerNum = 0;

    @Override
    protected int initLayout() {
        return R.layout.activity_hp_zao_yin_video;
    }

    @Override
    protected int initBR() {
        return 0;
    }

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle bundle) {
        binding.camera.setLifecycleOwner(this);
        //设置相机录像事件
        binding.camera.addCameraListener(new CameraListener() {
            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                super.onVideoTaken(result);
                //Log.e("录像完成", String.valueOf(result.getSize()));
                Utils.result = result;
                navigateTo(HpZaoYinVideoInfoActivity.class);
            }

            @Override
            public void onVideoRecordingStart() {
                super.onVideoRecordingStart();
                //Log.e("录像开始","");
            }

            @Override
            public void onVideoRecordingEnd() {
                super.onVideoRecordingEnd();
                //Log.e("录像结束","");

            }
        });
        //点击事件-返回
        binding.hpZaoYinPhotoBt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        //点击事件-摄像
        binding.hpZaoYinPhotoBt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (binding.camera.isTakingVideo()) {
                    //已经在录像状态时，关闭录像
                    binding.camera.stopVideo();
                    binding.hpZaoYinPhotoBt2.setImageResource(R.mipmap.module_hp_zao_yin_media_img2);
                    //关闭计时器
                    timerNum = 0;
                    binding.hpZaoYinVideoTime.setVisibility(View.INVISIBLE);
                } else {
                    //开始录像
                    AdUtils.INSTANCE.checkFunction(requireContext(), new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            //会员功能
                            binding.camera.takeVideoSnapshot(new File(requireContext().getFilesDir(), "video.mp4"));
                            binding.hpZaoYinPhotoBt2.setImageResource(R.mipmap.module_hp_zao_yin_media_img5);
                            //显示计时器
                            timerNum = 0;
                            binding.hpZaoYinVideoTime.setVisibility(View.VISIBLE);
                            //camera.takeVideoSnapshot(new File(getFilesDir(), "video.mp4"), 5000);
                            return null;
                        }
                    });
                }

            }
        });
        //点击事件-切换摄像头
        binding.hpZaoYinPhotoBt3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (binding.camera.isTakingPicture() || binding.camera.isTakingVideo()) {
                    return;
                }
                binding.camera.toggleFacing();
            }
        });
        //获取录音机权限
        audioRecordDemo = new AudioRecordVideoDemo2(this);
        getPermission();
        mHandler = new Handler(Looper.getMainLooper());
        startRepeatedTask();
    }

    //开启录音权限
    private void getPermission() {
        List<String> pre = new ArrayList<>();
        pre.add(Manifest.permission.RECORD_AUDIO);
        JtXXPermissions.INSTANCE.requestPermission(requireContext(), "", pre, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                audioRecordDemo.getNoiseLevel(new AudioRecordVideoDemo2.MonitorInterface() {
                    @Override
                    public void monitorListener(Double res) {
                        binding.hpZaoYinTv0.setText(res + "dB");
                        if (res > 0) {
                            numArr.add(res);
                            setNumArr();
                        }
                    }
                });
                return null;
            }
        });
    }

    //计算list最大，最小，平均值
    private void setNumArr() {
        Double maxNum = Collections.max(numArr);
        Double minNum = Collections.min(numArr);
        Double sum = 0.0;
        for (Double i : numArr) {
            sum += i;
        }
        Double avNum = sum / numArr.size();
        avNum = Math.round(avNum * 10) / 10.0;
        binding.hpZaoYinTv1.setText(maxNum + "dB");
        binding.hpZaoYinTv2.setText(avNum + "dB");
        binding.hpZaoYinTv3.setText(minNum + "dB");

    }

    private void startRepeatedTask() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // 执行任务逻辑
                setTime();
                // 继续下一次定时任务
                startRepeatedTask();
                //
                if (binding.camera.isTakingVideo()) {
                    timerNum++;
                    changeTimerView();
                }
            }
        }, 1000); // 1秒后执行
    }

    //改变录音时间
    private void changeTimerView() {
        //Log.e("计时器", String.valueOf(timerNum));
        String min = BaseUtils.INSTANCE.returnValue(timerNum / 60);
        String sec = BaseUtils.INSTANCE.returnValue(timerNum % 60);
        //binding.hpZaoYinVideoTime.setText(timerNum+"");
        binding.hpZaoYinVideoTime.setText(min + ":" + sec);
    }

    //设置时间方法
    private void setTime() {
        long m = System.currentTimeMillis() / 1000;
        binding.hpZaoYinPhotoTv1.setText(BaseUtils.INSTANCE.formatTime((int) m, "yyyy.MM.dd"));
        binding.hpZaoYinPhotoTv2.setText(BaseUtils.INSTANCE.formatTime((int) m, "HH:mm:ss"));
        binding.hpZaoYinPhotoLl.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding.camera.destroy();
        audioRecordDemo.sotp();
        mHandler.removeCallbacksAndMessages(null);
    }


}